use crate::models::countries::{self, CreateParams};
use axum::{
    Json, Router,
    extract::State,
    routing::{get, post},
};
use loco_rs::prelude::*;

pub fn routes() -> Router<AppContext> {
    Router::new()
        .route("/countries", post(create))
        .route("/countries/:id", get(get_by_id))
        .route("/countries/:id/delete", post(delete))
        .route("/countries/by-code/:code", get(get_by_code))
}

async fn create(
    State(state): State<AppContext>,
    Json(params): Json<CreateParams>,
) -> Result<Response> {
    let country = countries::Model::create(&state.db, &params).await?;
    format::json(country)
}

async fn get_by_id(
    State(state): State<AppContext>,
    axum::extract::Path(id): axum::extract::Path<String>,
) -> Result<Response> {
    let country = countries::Model::find_by_id(&state.db, &id).await?;
    format::json(country)
}

async fn delete(
    State(state): State<AppContext>,
    axum::extract::Path(id): axum::extract::Path<String>,
) -> Result<Response> {
    let country = countries::Model::find_by_id(&state.db, &id).await?;
    country.delete(&state.db).await?;
    format::json(())
}

async fn get_by_code(
    State(state): State<AppContext>,
    axum::extract::Path(code): axum::extract::Path<String>,
) -> Result<Response> {
    let country = countries::Model::find_by_code(&state.db, &code).await?;
    format::json(country)
}
